# mail_sender.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import logging
from typing import List
from config import EMAIL_CONFIG, EmailConfig

logger = logging.getLogger(__name__)

class EmailSender:
    """邮件发送器"""
    
    def __init__(self, config: EmailConfig):
        self.config = config
        self.smtp_server = config.smtp_server
        self.smtp_port = config.smtp_port
        self.sender_email = config.sender_email
        self.sender_password = config.sender_password
        self.receiver_emails = config.receiver_emails
    
    def send_alert(self, stock_name: str, stock_symbol: str, 
                  current_price: float, change_percent: float, 
                  change_amount: float, threshold: float) -> bool:
        """
        发送股票提醒邮件
        
        Args:
            stock_name: 股票名称
            stock_symbol: 股票代码
            current_price: 当前价格
            change_percent: 涨跌幅百分比
            change_amount: 涨跌额
            threshold: 阈值
            
        Returns:
            bool: 发送是否成功
        """

        color_value = "#ff4d4f"
        if threshold < 0:
            color_value = "#008F00"
        
        # 创建邮件内容
        subject = f"股票提醒: {stock_name}({stock_symbol}) 涨跌幅超过 {threshold}%"
        
        # HTML 邮件内容
        html_content = f"""
        <html>
        <body>
            <h2 style="color: #1890ff;">股票价格提醒</h2>
            <div style="background: #f5f5f5; padding: 20px; border-radius: 8px;">
                <h3>{stock_name} ({stock_symbol})</h3>
                <table style="width: 100%; border-collapse: collapse;">
                    <tr>
                        <td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>当前价格:</strong></td>
                        <td style="padding: 8px; border-bottom: 1px solid #ddd; color: {color_value}; font-weight: bold;">{current_price}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>涨跌幅:</strong></td>
                        <td style="padding: 8px; border-bottom: 1px solid #ddd; color: {color_value}; font-weight: bold;">{change_percent}%</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>涨跌额:</strong></td>
                        <td style="padding: 8px; border-bottom: 1px solid #ddd; color: {color_value}; font-weight: bold;">{change_amount}</td>
                    </tr>
                    <tr>
                        <td style="padding: 8px; border-bottom: 1px solid #ddd;"><strong>提醒阈值:</strong></td>
                        <td style="padding: 8px; border-bottom: 1px solid #ddd;">{threshold}%</td>
                    </tr>
                </table>
            </div>
            <p style="color: #666; margin-top: 20px;">
                此邮件由股票监控系统自动发送<br>
                发送时间: {self._get_current_time()}
            </p>
        </body>
        </html>
        """        
        return self._send(subject, html_content, "html")
    
    def send_error_notification(self, error_message: str) -> bool:
        """发送错误通知邮件"""
        subject = "股票监控系统错误"
        content = f"""
        股票监控系统遇到错误：
        
        错误信息: {error_message}
        
        时间: {self._get_current_time()}
        
        请及时检查系统运行状态。
        """
        return self._send(subject, content, "plain")

    def send_notification(self, message: str) -> bool:
        """发送通知邮件"""
        subject = "股票监控系统状态"
        content = f"""
        股票监控系统状态：{message}
        时间: {self._get_current_time()}
        """
        return self._send(subject, content, "plain")

    def _send(self, subject: str, content: str, content_type: str) -> bool:
        """
        邮件发送函数
        """
        try:
            message = MIMEMultipart()
            message['From'] = self.sender_email
            message['To'] = ', '.join(self.receiver_emails)
            message['Subject'] = Header(subject, 'utf-8')

            text_part = MIMEText(content, content_type, 'utf-8')
            message.attach(text_part)

            with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:
                    server.starttls()
                    server.login(self.sender_email, self.sender_password)
                    server.send_message(message)
            
            logger.info("发送邮件成功")
            return True

        except Exception as e:
            logger.error(f"发送邮件失败: {e}")
            return False            
    def _get_current_time(self) -> str:
        """获取当前时间字符串"""
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


# 创建全局邮件发送器实例
email_sender = EmailSender(EMAIL_CONFIG)